/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.statementView;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableRowSorter;

import com.ruipengkj.bean.MonthSaleSummaryView;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.base.query.PageIndex;
import com.ruipengkj.commons.base.query.PageModel;
import com.ruipengkj.commons.base.query.PageView;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.commons.util.exportExcel.MonthSaleSummaryExportUtil;
import com.ruipengkj.component.DataPackageComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonGray;
import com.ruipengkj.component.RPJButtonPrint;
import com.ruipengkj.component.jpanel.RPJPanelStatementTop;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.model.StatementMonthSaleSummaryViewModel;
import com.ruipengkj.service.StatmentMonthSaleSummaryViewService;
import com.ruipengkj.view.base.BasePagePanel;

/**
 * 说明：
 * 月度销售报表
 * @Author：黄盛强
 * @Date：2012-03-21
 */
public class StatmentMonthlySales extends BasePagePanel<MonthSaleSummaryView> implements  Runnable {
	private static final long serialVersionUID = 1L;
	private DataPackageComponent startTime;//开始日期
	private DataPackageComponent endTime; //结束日期
	
	private JButton selectButton;//选择
	private JButton clearButton;//清除按钮
//	private JButton printButton; //打印
	private JButton exportButton; //导出
//	private JButton exitButton; //退出
	
	private JTable table;
	private JScrollPane tableJsp;
	
	private PagingComponent pagingComponent;//翻页组件
	private PageView<MonthSaleSummaryView> pageView;//翻页主键
	private StatementMonthSaleSummaryViewModel monthSaleSummaryViewModel;
	private StatmentMonthSaleSummaryViewService monthSaleSummaryViewService;
	
//	create view ruipengkj_view_month_sale_summary as select 
//	b.OrderID as id,o.HappenTime,sum(c.SaleCount) as count,
//	sum(o.NeedMoney) as needMoney, sum(o.DiscountAmount) as discountAmount, 
//	c.name as commodityName from 
//	ruipeng_tb_TOrder as o,ruipeng_tb_TCommodity c, 
//	ruipeng_tb_tbillDetail as b where 
//	c.CommodityID=b.commodityid and b.billType = 3 and b.billId = o.OrderID 
//	group by EXTRACT(YEAR FROM o.HappenTime),EXTRACT(MONTH FROM o.HappenTime);

	public StatmentMonthlySales() {
		monthSaleSummaryViewService = BuildSpringApplication.getInstance().getStatmentMonthSaleSummaryViewServiceImpl();
		monthSaleSummaryViewModel = new StatementMonthSaleSummaryViewModel();
		this.setLayout(new BorderLayout());
		this.init();
		this.initListener();
	}
	
	private void init() {
		pageView = new PageView<MonthSaleSummaryView>();
		monthSaleSummaryViewModel=new StatementMonthSaleSummaryViewModel();
		table = uiFactory.createRPJTable(monthSaleSummaryViewModel, null, this, 30, JLabel.CENTER);
		tableJsp = new JScrollPane(table);
		
		this.setOpaque(true);
		this.setBackground(new Color(247, 252, 255));
		table.setOpaque(false);
		tableJsp.setOpaque(false);
		tableJsp.getViewport().setOpaque(false); 
		this.add(uiFactory.createFlowJPanel(), BorderLayout.WEST);
		this.add(uiFactory.createFlowJPanel(), BorderLayout.EAST);
		
		this.add(this.topPanel(),BorderLayout.NORTH);
		this.add(tableJsp,BorderLayout.CENTER);
		this.add(this.tailPanel(),BorderLayout.SOUTH);
		
		//排序
		TableRowSorter<StatementMonthSaleSummaryViewModel> tableRowSorter = new TableRowSorter<StatementMonthSaleSummaryViewModel>(
				monthSaleSummaryViewModel);
		table.setRowSorter(tableRowSorter);
	}
	
	private JPanel topPanel() {
		JPanel jp1 = new RPJPanelStatementTop();
		startTime = new DataPackageComponent("开始日期", 15);
		endTime = new DataPackageComponent("结束日期", 15);
		selectButton = new RPJButtonBlue("查询");
		clearButton=new RPJButtonGray("清空");
		jp1.add(startTime);
		jp1.add(endTime);
		jp1.add(selectButton);
		jp1.add(clearButton);
		return jp1;
	}
	
	private JPanel tailPanel() {
		JPanel tail_panel = uiFactory.createBorderJPanel();
		
		JPanel jp = uiFactory.createGridJPanel(1, 2);
		JPanel jp2 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		exportButton = new RPJButtonPrint("导 出");
		jp2.add(uiFactory.createJLabel("       "));
		jp2.add(exportButton);
		
		pagingComponent=new PagingComponent();
		pagingComponent.setPageDelegale(this);
		Util.setSize(pagingComponent, 80, 24);
		jp.add(jp2);
		jp.add(pagingComponent);
		
		tail_panel.add(jp);
		tail_panel.add(uiFactory.createFlowJPanel(), BorderLayout.NORTH);
		tail_panel.add(uiFactory.createFlowJPanel(), BorderLayout.SOUTH);
		return tail_panel;
	}
	
	private void initListener(){
		selectButton.addActionListener(this);
		exportButton.addActionListener(this);
		clearButton.addActionListener(this);
	}
	
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == selectButton){
			this.termQuery(1);
		} else if(e.getSource()==exportButton){
			//导出
			FileDialog fileDialog = new FileDialog(new JDialog(), "文件导出",FileDialog.SAVE);
			fileDialog.setVisible(true);
			String fileDir = fileDialog.getDirectory();
			String fileName = fileDialog.getFile();
			if (fileDir != null && !fileDir.equals("") && fileName != null&& !fileName.equals("")) {
				if (!fileName.toLowerCase().endsWith(".xls")) {
					if (fileName.lastIndexOf(".") != -1) {
						fileName = fileName.substring(0, fileName.lastIndexOf("."))+ ".xls";
					} else {
						fileName = fileName + ".xls";
					}
				}
				try {
					List<MonthSaleSummaryView> list = monthSaleSummaryViewService.findExportService(this.queryTerm());
					if (list != null && list.size() != 0) {
						exportButton.setEnabled(false);
						MonthSaleSummaryExportUtil.writeExcel(fileDir + fileName,list);
						JOptionPane.showMessageDialog(null, "导出成功");
					} else {
						JOptionPane.showMessageDialog(null, "数据为空，导出失败");
					}
				} catch (Exception e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, "导出失败");
				}
				exportButton.setEnabled(true);
			}
		} else if (e.getSource() == clearButton) {
			startTime.setDate(null); //时间1
			endTime.setDate(null); //时间2
		}
	}
	
	private MonthSaleSummaryView queryTerm() {
		MonthSaleSummaryView monthSaleSummaryView=new MonthSaleSummaryView();
		monthSaleSummaryView.setHappenTime(startTime.getDate());
		monthSaleSummaryView.setEndTime(endTime.getDate());
		return monthSaleSummaryView;
	}
	@Override
	protected void termQuery(final int currentPage){
		new Thread(){
			public void run(){
				tableJsp.getViewport().remove(table);
				tableJsp.getViewport().add(waitComponent);
				try {
					pageView.setCurrentPage(currentPage);
					PageModel<MonthSaleSummaryView> pageModel = monthSaleSummaryViewService.getScrollService(pageView.getFirstResult(), pageView.getMaxResult(),queryTerm());
					pageView.setPageModel(pageModel);
					pageView.setPageIndex(PageIndex.getPageIndex(pageView.getPageCode(), pageView.getCurrentPage(), pageView.getTotalPage()));
					if(pageModel!=null){
						TabelUtil.clearTableRowSorter(table);
						monthSaleSummaryViewModel.setRowData(pageModel.getResultList());
						SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
								tableJsp.getViewport().remove(waitComponent);
								tableJsp.getViewport().add(table);
								TabelUtil.setJTabelAutoClumnWidth(table);
								pagingComponent.show();
							}
						});
					}else{
						//没有订单数据
						tableJsp.getViewport().remove(waitComponent);
						tableJsp.getViewport().add(table);
						monthSaleSummaryViewModel.clear();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	@Override
	protected PageView<MonthSaleSummaryView> getPageView() {
		return pageView;
	}
	@Override
	public void run() {
		this.termQuery(1);
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub
		
	}
}
